package com.ohs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ohs.mapper.before.TradeMapper;
import com.ohs.pojo.*;
import com.ohs.service.ITradeService;
import com.ohs.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Service
public class TradeServiceImpl implements ITradeService {

    @Autowired(required = false)
    private TradeMapper tradeMapper;

    //查找所有的购物车记录
    @Override
    public String findAllShopCar(Model model, HttpSession session) {
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null){
            model.addAttribute("msg", "会话过期，请重新登录");
            return "before/error";
        }
        List<Product_ShopCar> shopCars = this.tradeMapper.findAllShopCars(userId);
        for (int i = 0; i < shopCars.size(); i++){
            Product_ShopCar p = shopCars.get(i);
            double total = p.getPrice() * p.getQuantity();
            //System.out.println(total);
            p.setTotal(total);
            shopCars.set(i, p);
        }
        if (shopCars.size() == 0){
            model.addAttribute("shopcarNull", 0);
        }else {
            model.addAttribute("shopCars", shopCars);
        }
        return "before/shopCar";
    }

    @Override
    public ResponseResult deleteShopCarByCarId(Integer carId) {
        QueryWrapper<ShopCar> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("carId", carId);
        int row = this.tradeMapper.delete(queryWrapper);
        if (row != 1){
            return new ResponseResult(201, "删除失败");
        }
        return new ResponseResult(200, "删除成功");
    }

    @Override
    public ResponseResult deleteBatchShopCar(List<Integer> carId) {
        if (carId.size() == 0){
            return new ResponseResult(201, "carId传输失败");
        }
        int row = this.tradeMapper.deleteBatchShopCar(carId);
        if (row == 0){
            return new ResponseResult(202, "删除失败");
        }
        return new ResponseResult(200, "删除成功");
    }

    @Override
    @Transactional
    public ResponseResult modifyQuantity(Integer carId, Integer quantity, Integer productId) {
        //System.out.println(carId +"数量:"+ quantity +":"+ productId);
        if(carId == null){
            return new ResponseResult(201, "carId参数有误");
        }
        if(quantity == null){
            return new ResponseResult(202, "quantity参数有误");
        }
        if(quantity == null){
            return new ResponseResult(203, "productId参数有误");
        }
        Product product = this.tradeMapper.findProductByPId(productId);
        //System.out.println(product);
        if (quantity > product.getAccount()){
            return new ResponseResult(204, "库存不足");
        }
        ShopCar shopCar = new ShopCar();
        shopCar.setCarId(carId);
        shopCar.setQuantity(quantity);
        int row = this.tradeMapper.updateById(shopCar);
        if (row != 1){
            return new ResponseResult(205, "数量改变失败");
        }
        return new ResponseResult(200, "数量改变成功");
    }

    @Override
    @Transactional
    public String toGenerateOrderPage(List<Integer> carId, Model model, HttpSession session) {
        if (carId == null){
            model.addAttribute("msg", "订单生成失败");
            return "before/error";
        }
        List<ShopCar> shopCar = this.tradeMapper.findShopCarProIdByCarId(carId);

        if (shopCar.size() == 0){
            model.addAttribute("msg", "订单信息查找失败");
            return "before/error";
        }
        List<Integer> proId = new ArrayList<>();
        for(ShopCar s: shopCar){
            proId.add(s.getProId());
        }
        //生成订单信息
        List<Product_ShopCar> generateOrderInfo = this.tradeMapper.findGenerateOrderInfoByProId(proId);
        Integer num = 0;
        for (int i = 0; i < generateOrderInfo.size(); i++){
            Product_ShopCar p = generateOrderInfo.get(i);
            double total = p.getPrice() * p.getQuantity();
            //System.out.println(total);
            p.setTotal(total);
            p.setTotalNum(num + p.getQuantity());
            num = p.getTotalNum();
            generateOrderInfo.set(i, p);
        }
        model.addAttribute("totalNum", num);
        model.addAttribute("generateOrderInfo", generateOrderInfo);

        //将订单信息封装到订单实体类
        List<Order> orders = new ArrayList<>();
        Order order = null;
        for (int i = 0; i < generateOrderInfo.size(); i++){
            order = new Order();
            Product_ShopCar p = generateOrderInfo.get(i);
            order.setUserId(p.getUserId());
            order.setProId(p.getProId());
            order.setNum(p.getQuantity());
            order.setPrice(p.getTotal());
            order.setStatus("待支付");
            order.setAddId(1);
            orders.add(order);
        }

        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null){
            model.addAttribute("msg", "会话过期，请重新登录");
            return "before/error";
        }
        //地址信息
        List<Address> address= this.tradeMapper.findAddressByUserId(userId);
        for (int i = 0; i < address.size(); i++){
            Address a = address.get(i);
            //上面得到的是code，
            String province = a.getProvince();
            String city = a.getCity();
            String area = a.getArea();

            //然后根据code查找相应的名字。
            //获取省份的名字
            String provinceName = this.tradeMapper.findDistrictByCode(province).getName();
            //获取城市的名字
            String cityName = this.tradeMapper.findDistrictByCode(city).getName();
            //获取县区的名字
            String areaName = this.tradeMapper.findDistrictByCode(area).getName();

            //获取详细地址
            String detail = a.getDetail();
            //全地址
            String districtInfo = provinceName + cityName + areaName + detail;
            a.setDetail(districtInfo);

            //重新放回去list
            address.set(i, a);
        }
        model.addAttribute("address", address);

        //删除购物车记录
        int row = this.tradeMapper.deleteBatchShopCar(carId);
        if (row == 0){
            model.addAttribute("msg", "购物车在生成订单时，删除购物车记录失败");
            return "before/error";
        }

        //生成订单状态是待支付
        if(orders.size() > 1){
            int row1 = this.tradeMapper.insertBatchOrder(orders);
            if (row1 == 0){
                model.addAttribute("msg", "购物车在生成订单时，购物车到生成订单记录失败");
                return "before/error";
            }
        }
        if (orders.size() == 1){
            int row2 = this.tradeMapper.insertOrder(order);
            if (row2 == 0){
                model.addAttribute("msg", "购物车在生成订单时，购物车到生成订单记录失败");
                return "before/error";
            }
        }
        return "before/generateOrder";
    }

    @Override
    public ResponseResult updateOrderStatusByUserIdAndProId(Integer userId, Integer proId) {
        int i = this.tradeMapper.updateOrderStatusByUserIdAndProId(userId, proId);
        if (i != 1){
            return new ResponseResult(201, "修改状态失败");
        }
        return new ResponseResult(200, "修改状态成功");
    }

    @Override
    public String findReceivedGoods(HttpSession session, Model model) {
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null){
            model.addAttribute("msg", "会话已过期，请重新登录");
            return "before/error";
        }
        List<Product_Order_Comment> receivedGoods = this.tradeMapper.findReceivedGoods(userId);
        //System.out.println(receivedGoods.size());
        model.addAttribute("receivedGoods", receivedGoods);
        return "before/OrderComment";
    }

    @Override
    public ResponseResult commentByUserIdAndProId(Integer userId, Integer proId, String comment) {
        if (userId == null){
            return new ResponseResult(201, "userId参数有误");
        }
        if (proId == null){
            return new ResponseResult(202, "proId参数有误");
        }
        if (comment == null){
            return new ResponseResult(203, "评论不许为空");
        }
        int i = this.tradeMapper.insertCommentByUserIdAndProId(userId, proId, comment);
        if (i != 1){
            return new ResponseResult(204, "评论失败");
        }
        this.tradeMapper.updateOrderSpareByUserIdAndProId(userId, proId);
        return new ResponseResult(200, "评论成功");
    }

    @Override
    public String findCommentByUserId(HttpSession session, Model model) {
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null){
            model.addAttribute("msg", "会话已过期，请重新登录");
            return "before/error";
        }
        List<Product_Order_Comment> commentedGoods = this.tradeMapper.findCommentedGoods(userId);
        model.addAttribute("commentedGoods", commentedGoods);
        return "before/OrderCommented";
    }

    @Override
    public ResponseResult findCommentsByCommentId(Integer commentId) {
        if (commentId == null){
            return new ResponseResult(201, "评论查找失败");
        }
        Comment comment = this.tradeMapper.findCommentsByCommentId(commentId);
        if(comment == null){
            return new ResponseResult(202, "评论查找失败");
        }
        String comments = comment.getComments();
        return new ResponseResult(200, comments);
    }

    @Override
    public ResponseResult updataComments(Integer commentId, String comments) {
        if (commentId == null){
            return new ResponseResult(201, "评论修改失败");
        }
        if (comments == null){
            return new ResponseResult(202, "评论修改失败");
        }
        int i = this.tradeMapper.updataComments(commentId, comments);
        if (i == 0){
            return new ResponseResult(203, "评论修改失败");
        }
        return new ResponseResult(200, "修改成功");
    }
}
